#!/usr/bin/env python
# coding=utf-8

from urlparse import urljoin
from urllib import urlopen
from HTMLParser import HTMLParser
import os
import sys
import re
import codecs
import football_url

'''
Created on 2009-3-19

@author: ylb
'''

HTML_FILEPATH = r'D:\tmp\yingchao1.htm'
OUTPUT_FILE = open(r'D:\tmp\tmp.txt', 'w')


class TestHTMPParser(HTMLParser):
	sys.stdout = OUTPUT_FILE
	def __init__(self):
		HTMLParser.__init__(self)
		self._tbody = 0
		self._tr = 0
		self._td = 0
		self._table = 0
		self._tree = ('root', [])
		self._nodeStack = [self._tree]
		self._tableCnt = 0

	def handle_starttag(self, tag, attrs):
		if tag.lower() == 'td':
			newNode = ('td', [])
			self._nodeStack[-1][1].append(newNode)
			self._nodeStack.append(newNode)
		elif tag.lower() == 'tr':
			newNode = ('tr', [])
			self._nodeStack[-1][1].append(newNode)
			self._nodeStack.append(newNode)
		elif tag.lower() == 'table':
			self._tableCnt += 1
			newNode = ('table', [])
			self._nodeStack[-1][1].append(newNode)
			self._nodeStack.append(newNode)


	def handle_endtag(self, tag):
		if tag.lower() == 'td':
			#self._nodeStack[-1].append('/td')
			self._nodeStack.pop()
		elif tag.lower() == 'tr':
			#self._nodeStack[-1].append('/tr')
			self._nodeStack.pop()
		elif tag.lower() == 'table':
			#self._nodeStack[-1].append('/table%s'%(self._tableCnt,))
			self._tableCnt -= 1
			self._nodeStack.pop()

	def handle_data(self, data):
		if self._nodeStack[-1] != self._tree:
			self._nodeStack[-1][1].append(data)
			#pass
			
	def fetch_tree(self):
		return self._tree


def main():
	s = urlopen(urljoin(football_url.siteBaseUrl,football_url.yingchao)).read()
	s = s.decode('gbk')
	mp = TestHTMPParser()
	mp.feed(s)
	t = mp.fetch_tree()
	print t

if __name__ == '__main__':
	main()

